package de.jmda.cbo.user;

import static java.lang.System.currentTimeMillis;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

/**
 * A registration request is created by the system to indicate, that a new user
 * has requested to become a registered user. A persisted registration request
 * consists at least of an unique {@link #username} and a {@link
 * #registrationCode}. The system generated registration code is a surrogate for
 * a user's password as long as the user did not provide a password himself.
 *
 * @author rwegner
 */
@NamedQueries
({
	@NamedQuery(
			name=RegistrationRequest.QUERY_ALL,
			query="select r from " + RegistrationRequest.TABLENAME + " r"),
	@NamedQuery(
			name=RegistrationRequest.QUERY_COUNT,
			query="select count(r) from " + RegistrationRequest.TABLENAME + " r"),
	@NamedQuery(
			name=RegistrationRequest.QUERY_BY_USERNAME,
			query="select r from " + RegistrationRequest.TABLENAME + " r where r.username = :username")
})
@Entity
public class RegistrationRequest implements Serializable
{
	private static final long serialVersionUID = 1L;

	public final static String TABLENAME = "RegistrationRequest";
	public final static String QUERY_ALL = TABLENAME + "All";
	public final static String QUERY_COUNT = TABLENAME + "Count";
	public final static String QUERY_BY_USERNAME = TABLENAME + "ByUsername";

	@Id
	@GeneratedValue
	private long id;

	/**
	 * authentification data: username
	 */
	@Column(unique=true, nullable=false)
	private String username;

	/**
	 * authentification data: system generated registration code (surrogate for
	 * user provided password)
	 */
	@Column(nullable=false)
	private String registrationCode;

	/**
	 * email address of requesting new user
	 */
	@Column(nullable=false)
	private String email;

	/**
	 * required by JPA with at least package visibility
	 */
	RegistrationRequest()
	{
		super();
	}

	public RegistrationRequest(String username, String email)
	{
		this();

		// TODO parameter check
		this.username = username;
		this.registrationCode = Encryptor.encryptPassword("" + currentTimeMillis());
		this.email = email;
	}

	public long getId()
	{
		return this.id;
	}

	public String getUsername()
	{
		return username;
	}

	public String getRegistrationCode()
	{
		return registrationCode;
	}

  public String getEmail()
	{
		return email;
	}

	public String asString()
  {
	  return "User [" +
	  		"id=" + id + ", " +
	  		"username="+ username + ", " +
	  		"registrationCode="+ registrationCode + "]";
  }
}